package dsl.rulesengine


class RulesEngineDelegator {

    def rulesLogic
    def availableMethods = [:]

    RulesEngineDelegator(rulesLogic) {
        this.rulesLogic = rulesLogic
        rulesLogic.class.methods.each {
            availableMethods[it.name] = it
        }
    }

    def start() {
        return true
    }

    //the order of the arguments is not defined in the order that they are passed into the method call!    
    public Object invokeMethod(String name, Object arguments) {
        def closures = []
        def basicArgs = []
        arguments.each {
            if(it instanceof Closure) {
                closures << it
            } else {
                basicArgs << it
            }
        }

        def result = delegateRule(name, basicArgs)
        if(result) {

            closures.each {
                it.delegate = this
                it.call()
            }
        }
        return this
    }

    def delegateRule(name, args) {
        if(availableMethods[name]) {
            return rulesLogic.invokeMethod(name, (args.size() == 0)?null:args.toArray())
        } else {
            return this.metaClass.invokeMethod(this, name, (args.size() == 0)?null:args.toArray())
        }

    }

}